﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using CueMounter.DokanStructure;

namespace CueMounter {
	public class WaveFile : IBinaryProvider {
		const int BufferSize = 4096;
		private byte[] waveBuffer;
		public WaveHeader Header;
		public IWaveProvider WaveProvider;

		public WaveFile(IWaveProvider waveProvider) {
			Header = new WaveHeader((int)waveProvider.Length, waveProvider.Channels, waveProvider.SampleRate, waveProvider.BitsPerSample);
			WaveProvider = waveProvider;
			waveBuffer = new byte[BufferSize];
		}

		public void Dispose() {
			WaveProvider.Dispose();
		}

		public long Length {
			get {
				return Header.Data.Length + WaveProvider.Length;
			}
			set
			{
				throw new NotSupportedException();
			}
		}

		public bool CanRead { get { return true; } }
		public bool CanWrite { get { return false; } }

		public long Read(long fileOffset, byte[] buffer, long bufferOffset, long length) {
			long copied = 0;
			if(fileOffset < Header.Data.Length) {
				long copyLength = Math.Min(Header.Data.Length - fileOffset, length);
				Array.Copy(Header.Data, fileOffset, buffer, bufferOffset, copyLength);

				fileOffset += copyLength;
				bufferOffset += copyLength;
				length -= copyLength;

				copied += copyLength;
			}
			if(length > 0) {
				copied += WaveProvider.Read(fileOffset - Header.Data.Length, buffer, bufferOffset, length);
			}
			return copied;
		}


		public long Write(long fileOffset, byte[] buffer, long bufferOffset, long length)
		{
			throw new NotSupportedException();
		}
	}
}
